<template>
  <div class="registerDetail">
    <van-nav-bar
      :fixed="true"
      :placeholder="true"
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 跟踪单详情 -->
    <div class="detail_header flex">
      <div class="detail_header_lt" @click="goCarDetail()">
        <div class="carNo flex">
          {{ dataSource.carNo }}
          <i class="iconfont icon-right"></i>
        </div>
        <div class="hank">{{ dataSource.customerName }}</div>
      </div>
      <div class="detail_header_rt flex">
        <a class="flex" @click="handleTel(dataSource.mobile1)">
          <i class="iconfont icon-tel"></i>
        </a>
        <div @click="getExList(dataSource)" class="iconfont icon-wx"></div>
      </div>
    </div>

    <!-- 表单 -->
    <div class="formData">
      <van-form>
        <van-field
          v-model="dataSource.fixCenterName"
          name="维修中心"
          label="维修中心"
          input-align="right"
          readonly
        />
        <van-field
          v-model="dataSource.empName"
          name="服务顾问"
          label="服务顾问"
          input-align="right"
          readonly
        />
        <van-field
          v-model="dataSource.billStatus"
          name="单据状态"
          label="单据状态"
          input-align="right"
          readonly
        />
        <van-field
          clickable
          name="currentDate"
          :value="dataSource.bizDate"
          input-align="right"
          label="预约日期"
          readonly
        />
        <van-field
          clickable
          name="currentDate"
          :value="dataSource.dateIn"
          input-align="right"
          label="预约进场时间"
          readonly
        />
        <van-field
          v-model="dataSource.bookingType"
          name="预约类型"
          label="预约类型"
          input-align="right"
          readonly
        />
        <van-field
          v-model="dataSource.workBillType"
          name="工单类型"
          label="工单类型"
          input-align="right"
          readonly
        />
        <van-field
          v-model="dataSource.repairPrice"
          name="维修价格类型"
          label="维修价格类型"
          input-align="right"
          readonly
        />
        <van-field
          v-model="dataSource.mterialPriceType"
          name="配件价格类型"
          label="配件价格类型"
          input-align="right"
          readonly
        />

        <van-field
          v-model="dataSource.remark"
          name="备注"
          label="备注"
          type="textarea"
          input-align="left"
          readonly
          autosize
        />
      </van-form>

      <div class="cancelbox" v-if="dataSource.billStatus == '取消'">
        <van-field
          clickable
          name="取消日期"
          label="取消日期"
          :value="dataSource.cancelDate"
          input-align="right"
          readonly
        />
        <van-field
          clickable
          name="下次预约时间"
          :value="dataSource.nextBookingDate"
          input-align="right"
          label="下次预约时间"
          readonly
        />
        <van-field
          v-model="dataSource.bookingCancel"
          name="取消原因"
          label="取消原因"
          type="textarea"
          input-align="left"
          readonly
        />
      </div>

      <!-- 底部按钮 -->
      <div class="footerBtn">
        <div class="submitBtn flex">
          <div
            class="btnbox cancelBtn"
            @click="cancelApply"
            v-if="dataSource.billStatus != '取消'"
          >
            取消预约
          </div>
          <div
            class="btnbox editBtn"
            v-if="dataSource.billStatus == '保存'"
            @click="editApply"
          >
            编辑
          </div>
        </div>
      </div>
    </div>
    <van-dialog
      v-model="showDialog"
      title=""
      show-cancel-button
      :showConfirmButton="false"
    >
      <div class="contact_list">
        <div
          class="contact_item flex"
          v-for="(item, index) in contactList"
          :key="index"
        >
          <div class="contact_lt flex">
            <img v-if="item.avatar" class="contact_header" :src="item.avatar" />
            <div class="contact_name">
              {{ item.remark ? item.remark : item.name }}
            </div>
            <div class="contact_com_wx" v-if="item.type == 1">@微信</div>
            <div class="contact_com" v-if="item.type == 2">
              @{{ item.corpName ? item.corpName : item.corpFullName }}
            </div>
          </div>
          <div class="contact_btn" @click="runWxChat(item)">联系</div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { Search, Field, Form, Toast, Dialog, Notify } from "vant";
import repairApi from "@/api/repairApi";
import commonApi from "@/api/commonApi";
import { getCookies, isPhone } from "@/utils/util.js";
import axios from "axios";
import qs from "qs";
const base_url = process.env.BASE_API;
export default {
  name: "applyRepairEdit",
  components: {
    Search,
    Field,
    Form,
    Toast,
    Notify,
    Dialog,
  },
  data() {
    return {
      dataSource: {
        billId: "", //单据ID
        vinCode: "", //车架号
        carNo: "", //车牌号
        customerName: "", //客户名称
        billStatus: "", //单据类型
        mobile1: "", //手机号1
        mobile12: "", //手机号2
        empName: "", //所属服务顾问
        fixCenterName: "", //维修中心
        bookingType: "", //预约类型
        bizDate: "", //预约时间,
        dateIn: "", //预约进场时间,
        carModel: "", //车型
        workBillType: "", //工单类型
        materialPriceType: "", //配件价格
        repairpricetype: "", //维修价格类型
        remark: "", //备注
      },
      userId: getCookies("userId"),
      detailId: "",
      showDialog: false,
      contactList: [],
    };
  },

  mounted() {
    if (localStorage.getItem("applyBillId")) {
      this.detailId = localStorage.getItem("applyBillId");
      this.getDetail(this.detailId);
    }
  },
  methods: {
    // 获取外部联系人信息
    getExList(data) {
      axios({
        url: `${base_url}/proxy/ext/user/getExList`,
        method: "post",
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { carNo: data.carNo, name: data.customerName },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token"),
        },
      }).then((res) => {
        if (res.data && res.data.data && res.data.data.length != 0) {
          this.contactList = res.data.data;
          this.showDialog = true;
        } else {
          Notify({ type: "danger", message: "未找到相关联系人" });
        }

        console.log("获取外部联系人信息:", res);
      });
    },
    runWxChat(data) {
      let vm = this;
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: "post",
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { url: location.href.split("?")[0], type: "app" },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token"),
        },
      }).then((res) => {
        console.log("jsdkConfig:", res);
        let jsdk = res.data.data;
        localStorage.setItem("jsdk", JSON.stringify(res.data.data));
        wx.agentConfig({
          corpid: jsdk.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
          agentid: jsdk.agentid, // 必填，企业微信的应用id （e.g. 1000247）
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
          jsApiList: ["openEnterpriseChat"], //必填，传入需要使用的接口名称
          success: function (res) {
            console.log("agentConfig权限成功返回信息:", res);
            wx.openEnterpriseChat({
              // 注意：userIds和externalUserIds至少选填一个。内部群最多2000人；外部群最多500人；如果有微信联系人，最多40人
              userIds: "", //参与会话的企业成员列表，格式为userid1;userid2;...，用分号隔开。
              externalUserIds: data.externalUserid, // 参与会话的外部联系人列表，格式为userId1;userId2;…，用分号隔开。
              groupName: "", // 会话名称。单聊时该参数传入空字符串""即可。
              chatId: "", // 若要打开已有会话，需指定此参数。如果是新建会话，chatId必须为空串
              success: function (res) {
                var chatId = res.chatId; //返回当前群聊ID，仅当使用agentConfig注入该接口权限时才返回chatId
                // 回调
              },
              fail: function (res) {
                if (res.errMsg.indexOf("function not exist") > -1) {
                  alert("版本过低请升级");
                }
              },
            });
          },
          fail: function (res) {
            console.log("agentConfig权限失败返回信息:", res);
            if (res.errMsg.indexOf("function not exist") > -1) {
              alert("版本过低请升级");
            }
          },
        });
      });
    },
    getDetail(billId) {
      repairApi
        .queryRepairBookingById({
          billId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.dataSource = res.data;
            // localStorage.setItem('billId', '')
          }
        });
    },

    cancelApply() {
      localStorage.setItem("billId", this.dataSource.billId);
      this.$router.push({
        path: "/applyRepairCancel",
      });
    },
    // 编辑
    editApply() {
      this.$router.push({
        path: "/applyRepairEdit",
        query: { billId: this.dataSource.billId },
      });
    },
    handleTel(tel) {
      if (isPhone()) {
        window.location.href = `tel:${tel}`;
      } else {
        Toast("请在手机端使用此功能");
      }
    },
    goCarDetail() {
      this.$router.push({
        path: "/carOrderDetail",
        query: { billId: this.dataSource.carId },
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  overflow: hidden;
  background: #f3f3f3;
  padding-bottom: 1.5rem;

  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .icon-right {
          margin-left: 0.2rem;
          color: #409eff;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.2rem;
      }
      .icon-wx {
        color: #409eff;
        font-size: 0.65rem;
      }
    }
  }
  .formData {
    background: #fff;
    padding-bottom: 0.5rem;
  }
}
/deep/.van-field__error-message {
  text-align: right;
}
.footerBtn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  padding-bottom: 0.4rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);

  .submitBtn {
    width: 80%;
    margin: auto;
    margin-top: 0.3rem;
    justify-content: space-between;
    overflow: hidden;
    box-sizing: content-box;

    .btnbox {
      width: 100%;
      font-size: 0.28rem;
      padding: 0.25rem 0;
      border-radius: 5px;
      text-align: center;
      color: #fff;
      box-sizing: content-box;
    }
    .editBtn {
      background: #409eff;
    }
    .cancelBtn {
      background: #e31010;
      margin-right: 10px;
    }
  }
}

.cancelbox {
  border-top: 5px solid #f3f3f3;
  margin-bottom: 1.5rem;
}
.contact_list {
  padding: 0.5rem 0.2rem 0 0.2rem;
  .contact_item {
    justify-content: space-between;
    margin-bottom: 20px;
  }
  .contact_lt {
    font-size: 0.28rem;
    color: #23ec1c;
    .contact_header {
      width: 30px;
      height: 30px;
      display: block;
      border-radius: 5px;
      margin-right: 5px;
    }

    .contact_name {
      font-size: 0.28rem;
      color: #333;
      margin-left: 5px;
    }
    .contact_com {
      color: #f65e07;
      font-size: 0.28rem;
    }
    .contact_com_wx {
      color: #23ec1c;
      font-size: 0.28rem;
    }
  }
  .contact_btn {
    background: #409eff;
    color: #fff;
    padding: 5px 15px;
    border-radius: 3px;
    font-size: 0.28rem;
  }
}
</style>
